﻿using AutoMapper;
using B.S.Base.Write.API.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class AddAccountCommandHandLer : IRequestHandler<AddAccountCommand, APIResult<int>>
    {
        IBaseRepostiy<AccountModel> _accountModel;
        IMapper _mapper;

        public AddAccountCommandHandLer(IBaseRepostiy<AccountModel> accountModel, IMapper mapper)
        {
            _accountModel = accountModel;
            _mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(AddAccountCommand request, CancellationToken cancellationToken)
        {
           var query= await _accountModel.GetAll().FirstOrDefaultAsync(x=>x.AccountName == request.AccountName && x.IsDeleted == false);
            {
                if(query != null)
                {
                    return new APIResult<int>
                    {
                        Code = ResultCode.Fail,
                        Message = "用户重复"
                    };
                }
            }
            var list=_mapper.Map<AccountModel>(request);
            list.Pwd = "123456";
            list.CreateUserTime = DateTime.Now;
             await _accountModel.AddAsync(list);
            return new APIResult<int>
            {
                Code = ResultCode.Ok,
                Data = 1,
                Message = "添加成功"
            };
        }
    }
}
